<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use DB;
use Image;

class UploadController extends BaseController
{
    public function index(Request $request)
    {
        if (!$request->hasFile('file')) return jsonFailed('不存在上传文件');
        $file = $request->file('file');
        $ext = $file->extension() ? $file->extension() : 'png';
        $file_name = md5(time()) . '.' . $ext;
        $dir_path = 'upload/' . date('Ymd') . '/';
        $file->move($dir_path, $file_name);
        $file_path = $dir_path . $file_name;
        $file_absolute_path = '/' .  $file_path;

        // 限制图片最大宽度为1000px
        $image = Image::make($file_path);
        if ($image->width() > 1000) {
            $image->resize(1000, null, function ($constraint) {
                $constraint->aspectRatio();
            });
            $image->save();
        }

        return jsonSuccess($file_absolute_path);
    }
}
